﻿using CatUtils.Utils.Currency;
using CatUtils.Utils.Currency.IoUtils;
using CatUtils.Utils.Currency.TextUtils;
using CatUtils.Utils.SpecialUtils.Html;
using CatUtilsDll.Utils.Currency.WebUtils;
using RabbitDownload.Helper;
using RabbitDownload.Helper.Currency;

using System;
using System.Collections.Generic;
using System.Linq;
using static RabbitDownload.WebSite.Konachan.KonachanStaticValue;

namespace RabbitDownload.WebSite.Konachan
{
    internal class KonachanTool
    {
        /// <summary>
        /// 获取图片列表
        /// </summary>
        /// <param name="Api">API</param>
        /// <param name="Rating">图片等级</param>
        /// <param name="Score">评分</param>
        /// <param name="OpenExclude">开启屏蔽词</param>
        /// <param name="OpenLog">启用日志</param>
        /// <returns></returns>
        public List<string> GetImgList(string Api, string Rating, int Score, bool OpenExclude, bool OpenLog)
        {
            List<string> TempList = new List<string>();
            foreach (KonachanInfo Single in GetKonachanInfo(Api))
            {
                int PostScore = Single.ImgScore;
                string ImgLink = Single.FileUrl;
                int PostId = Single.ImgId;
                string PostRating = Single.Rating;
                Console.WriteLine("评分{0}，安全等级{1}，id{2}", PostScore, PostRating, PostId);

                if (!GetModeFlag(PostRating, Score, PostScore) ||//获取模式和评分是否符合
                    TagExlude(Single.TagList, StaticValueOld.OldLogPath + "KonachanList.lst", OpenExclude)//查询标签是否有不合格
                   || LogExlude(ImgLink, StaticValueOld.ExcludePath, OpenExclude)//查询标签是否有不合格
                   )
                {
                    continue;
                }
                TempList.Add(Single.FileUrl);
            }

            return TempList;
        }

        /// <summary>
        /// 通过API解析相关信息
        /// </summary>
        /// <param name="API"></param>
        /// <returns></returns>
        public List<KonachanInfo> GetKonachanInfo(string API)
        {
            String Shtml = WebHelper.HttpPcGet(API);
            return GetImgInfo(Shtml);
        }

        /// <summary>
        /// 获取K站信息
        /// </summary>
        /// <param name="Shtml"></param>
        /// <returns></returns>
        public List<KonachanInfo> GetImgInfo(string Shtml)
        {
            List<KonachanInfo> konachanInfoList = new List<KonachanInfo>();

            foreach (string SinglePost in HtmlHelper.GetHtmlValueList(Shtml, "//posts/post"))
            {
                KonachanInfo konachanInfo = new KonachanInfo();
                konachanInfo.ImgScore = TextHelper.StringToInt(
                    HtmlHelper.GetFirstAttributes(SinglePost, "score", "//post")

                    );
                konachanInfo.ImgId = TextHelper.StringToInt(
                      HtmlHelper.GetFirstAttributes(SinglePost, "id", "//post")
                    );
                konachanInfo.FileUrl = HtmlHelper.GetFirstAttributes(SinglePost, "file_url", "//post");
                konachanInfo.Rating = HtmlHelper.GetFirstAttributes(SinglePost, "rating", "//post");
                konachanInfo.TagList = GetAllTag(SinglePost);
                konachanInfo.Source = HtmlHelper.GetFirstAttributes(SinglePost, "source", "//post");
                konachanInfoList.Add(konachanInfo);
            }
            return konachanInfoList;
        }

        /// <summary>
        /// 读取所有标签
        /// </summary>
        /// <param name="SinglePost"></param>
        /// <returns></returns>
        private List<string> GetAllTag(string SinglePost)
        {
            string PostTags = HtmlHelper.GetFirstAttributes(SinglePost, "tags", "//post");
            return PostTags.Split(Convert.ToChar(" ")).ToList<string>();
        }

        /// <summary>
        ///处理单个链接，并启用日志辅助模式，若需要跳过返回true
        /// </summary>
        /// <param name="SinglePostXml"></param>
        /// <param name="ExcludeFile">屏蔽关键词列表</param>
        /// <param name="OpenExclude"></param>
        /// <returns></returns>
        private bool LogExlude(string LogLink, string OldLogPath, bool OpenExclude)
        {
            if (!OpenExclude)
                //如果不启动屏蔽模块，直接返回结果
                return false;
            List<string> LogLinkList = new List<string>() { LogLink };
            List<string> ExcludeList = FileHelper.ReadAllLine(OldLogPath);
            return TagExlude(LogLinkList, ExcludeList);
        }

        /// <summary>
        ///获取单个图片标签，并启用TAG辅助模式，若需要跳过返回true
        /// </summary>
        /// <param name="SinglePostXml"></param>
        /// <param name="ExcludeFile">屏蔽关键词列表</param>
        /// <param name="OpenExclude"></param>
        /// <returns></returns>
        private bool TagExlude(List<string> TextValueList, string ExcludeFile, bool OpenExclude)
        {
            if (!OpenExclude)
                //如果不启动屏蔽模块，直接返回结果
                return false;

            List<string> ExcludeList = FileHelper.ReadAllLine(ExcludeFile);
            return TagExlude(TextValueList, ExcludeList);
        }

        /// <summary>
        /// 启用TAG辅助模式，若需要跳过返回true
        /// </summary>
        /// <param name="TextValueList"></param>
        /// <param name="ExcludeList"></param>
        /// <returns></returns>
        private bool TagExlude(List<string> TextValueList, List<string> ExcludeList)
        {
            foreach (string Line in TextValueList)
            {
                if (Line == "")
                    continue;

                if (ExcludeList.Contains(Line))
                {
                    Console.WriteLine("捕获到关键词【{0}】,跳过", Line);
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 获取扫描用模式
        /// </summary>
        /// <param name="rating"></param>
        /// <param name="score"></param>
        /// <returns></returns>
        public bool GetModeFlag(string Rating, int Score, int PostScore)
        {
            switch (KonachanStaticValue.DownLoadMode)
            {
                case "仅下载安全":
                    return SafeMode(Rating, Score, PostScore);

                case "安全+擦边球":
                    return QuestionableMode(Rating, Score, PostScore);

                case "全部下载（含色情）":
                    return ExplicitMode(Score, PostScore);
            }
            return true;
        }

        /// <summary>
        /// 全部下载，包括色情
        /// </summary>
        /// <param name="rating"></param>
        /// <param name="score"></param>
        /// <returns></returns>
        private bool ExplicitMode(int Score, int PostScore)
        {
            return CompreedScore(Score, PostScore);
        }

        /// <summary>
        /// 擦边球/可疑模式
        /// </summary>
        /// <param name="rating"></param>
        /// <param name="score"></param>
        /// <returns></returns>
        private bool QuestionableMode(string rating, int Score, int PostScore)
        {
            if (rating != "s" || rating != "q")
                return false;

            return CompreedScore(Score, PostScore);
        }

        /// <summary>
        /// 安全模式
        /// </summary>
        /// <param name="rating"></param>
        /// <param name="score"></param>
        /// <returns></returns>
        private bool SafeMode(string rating, int Score, int PostScore)
        {
            if (rating != "s")
                return false;

            return CompreedScore(Score, PostScore);
        }

        /// <summary>
        /// 对比分数，返回结果
        /// </summary>
        /// <param name="score"></param>
        /// <returns></returns>
        private bool CompreedScore(int Score, int PostScore)
        {
            if (Score != 0 && Score <= PostScore)
            {
                Console.WriteLine("评分{0}小于预设{1}，需要跳过", Score, KonachanStaticValue.ImgScore);
                return false;
            }
            return true;
        }
    }
}